package com.itheima.controller;


import com.itheima.utils.RequestUtils;
import com.itheima.vo.UserVo;

import com.itheima.entity.Result;

import com.itheima.pojo.User;
import com.itheima.service.WebUserLoginService;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;


@RestController
@RequestMapping("/login")
public class WebLoginController {

    @Autowired
    private WebUserLoginService userLoginService;




    /***
     * 登录
     * @param userVO
     * @return
     */

    @PostMapping("/login")
    public Result login(@RequestBody UserVo userVO) {


        Map map = userLoginService.userLogin(userVO);
        //登录是否成功
        boolean login =(boolean) map.get("login");
        //登录信息
        User user = (User) map.get("user");
        //登录失败
        if (!login){
            if (user.getLoginCount() >= 5) {
                return new Result( "密码输错次数过多,已被锁定30分钟");
            }
        }

        //将登陆成功的标记存到session中
        HttpSession session = RequestUtils.getHttpServletRequest().getSession();
        session.setAttribute("user",user);

        return new Result( "登录成功");
    }


    @PostMapping("/register")
    public Result register(@RequestBody UserVo userVO) {
        Integer num = userLoginService.userRegister(userVO);
        if (num > 0) {
            return new Result("注册成功");
        }
        if (num == 0) {
            return new Result("用户名重复或密码过短");
        }
        return new Result("注册失败");
    }

}
